﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using Castle.ActiveRecord;
using System.Web.UI;
using System.IO;
using SimplePMT.Data;
using SimplePMT.Components;
using NHibernate.Expression;

namespace SimplePMT.Control
{
    public partial class QuickTimeEntryControl : System.Web.UI.UserControl
    {
        public string attachmentList = string.Empty;
        public string svnList = string.Empty;
        public int attachmentCount = 0;
        public int svnCount = 0;
        public int qaReportItemCount = 0;
        public bool edit = false;
        public int taskid = 0;
        public Task task;
        public string taskTitle = "New Task";
        public string createdBy = string.Empty;
        public string createDate = string.Empty;
        public string assignDate = string.Empty;
        public string assignedTo = string.Empty;
        public string taskLocation = string.Empty;
        public string taskNotes;
        public int taskTypeId = 0;
        public int taskPriorityId = 0;
        public string[] taskPriorityOptions;
        public string[] taskTypeOptions;
        public string[] taskStateOptions;
        public string taskComplete = string.Empty;
        public int taskContainerId = 0;
        public string[] complexityOptions;
        public string[] memberOptions;
        public enum StateOptions { IsAccepted, IsOnHold, IsActive, IsResolved };
        public int stateOptionSelected = 0;
        public string[] releaseOptions;
        public int selectedRelease;
        public decimal taskHours = 0;
        public bool ReadOnly = false;

        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        public string[] BuildReleaseList(int ParentTaskContainerID)
        {
            Release[] releaseItems = Release.FindAll(Expression.Eq("DateReleased", Convert.ToDateTime("1/1/1900")), Expression.Eq("TaskContainerID", ParentTaskContainerID));
            string[] releaseList = new string[releaseItems.Length + 1];
            using (new SessionScope())
            {
                int i = 1;
                releaseList[0] = "0=SELECT RELEASE";
                foreach (Release release in releaseItems)
                {
                    if (release.Revision.Equals(0))
                    {
                        releaseList[i] = release.ID + "=" + release.Major + "." + release.Minor + "." + release.Build;
                        i++;
                    }
                }
            }
            return releaseList;
        }

        public override string ToString()
        {

            
            
            if (Session["MemberID"] != null)
            {
                Member member = Member.Find(Convert.ToInt32(Session["MemberID"]));
                ReadOnly = member.ReadOnly;
            }
            if (Request.QueryString["cid"] != null)
            {
                taskContainerId = Convert.ToInt32(Request.QueryString["cid"]);
            }
            releaseOptions = BuildReleaseList(Common.GetRecursiveTaskTreeID(TaskContainer.Find(taskContainerId)));
            complexityOptions = BuildTaskComplexityOptions(TaskComplexity.FindAll());
            memberOptions = BuildMemberList();

            using (new SessionScope())
            {
                taskLocation = Common.GetRecursiveTaskTreePath(TaskContainer.Find(taskContainerId));
                task = Task.Find(taskid) ?? new Task();
                selectedRelease = task.ReleaseID;
                svnList = BuildSVNCommits(task.ID);
                attachmentList = BuildAttachmentList(task.ID);
                taskStateOptions = new string[] { "0=New", "1=Accepted", "2=On Hold", "3=Working On", "4=Ready For QA" };
                if (task.ID > 0)
                {
                    TaskNote[] tna = TaskNote.FindAll(Expression.Eq("Task", task));
                    foreach (TaskNote tn in tna)
                    {
                        taskHours += tn.Hours;
                    }
                    taskTitle = task.Title.Replace("\"", "&quot;");
                    createDate = task.CreateDateTime.Value.ToShortDateString();
                    if (task.AssignedDateTime.HasValue)
                    {
                        assignDate = task.AssignedDateTime.Value.ToShortDateString();
                    }
                    if (!task.ClosedDateTime.Equals(new DateTime(1900,1,1)) || ReadOnly)
                    {
                        edit = false;
                        taskComplete = "1";
                    }
                    else
                    {
                        taskComplete = "0";
                    }
                    if (task.IsOnHold)
                    {
                        stateOptionSelected = 2;
                    }
                    else if (task.IsAccepted)
                    {
                        stateOptionSelected = 1;
                    }
                    else if (task.IsWorking)
                    {
                        stateOptionSelected = 3;
                    }
                    else if (task.IsResolved)
                    {
                        stateOptionSelected = 4;
                    }
                    else
                    {
                        stateOptionSelected = 0;
                    }
                    taskTypeId = task.TaskType.ID;
                    taskPriorityId = task.Priority.ID;
                    taskTypeOptions = BuildTaskTypeOptions(TaskType.FindAll());
                    taskPriorityOptions = BuildTaskPriorityOptions(Priority.FindAll());

                    taskNotes = TaskView.GetTaskNotes(task.ID);
                    TaskContainerItem ti = new TaskContainerItem();
                    TaskContainerItem[] containerItems = TaskContainerItem.FindAllByProperty("TaskID", task.ID);
                    if (containerItems.Length > 0)
                    {

                        if (containerItems[0].TaskContainer.ParentContainerID > 0)
                        {
                            taskLocation = Common.GetRecursiveTaskTreePath(TaskContainer.Find(containerItems[0].TaskContainer.ParentContainerID)) + " : " + containerItems[0].TaskContainer.Label;
                        }
                        else
                        {
                            taskLocation = containerItems[0].TaskContainer.Label;
                        }
                    }
                    Member created = Member.Find(task.CreateMemberID);
                    createdBy = created.FirstName + " " + created.LastName;
                    if (task.AssignedMemberID > 0)
                    {
                        Member assigned = Member.Find(task.AssignedMemberID);
                        assignedTo = assigned.FirstName + " " + assigned.LastName;
                    }
                }
                else
                {
                    taskTypeId = 0;
                    task.ClosedDateTime = new DateTime(1900, 1, 1);
                    taskPriorityId = 0;
                    taskTypeOptions = BuildTaskTypeOptions(TaskType.FindAll());
                    taskPriorityOptions = BuildTaskPriorityOptions(Priority.FindAll());
                    taskNotes = "";
                    createdBy = Session["FullName"].ToString();
                    createDate = DateTime.Now.ToShortDateString();
                }
            }

            string result = "";
            StringWriter writer = new StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
            this.Render(htmlWriter);
            result = writer.ToString();
            return result;
        }

        private string BuildSVNCommits(int taskId)
        {
            StringBuilder sb = new StringBuilder();
            SvnCommit[] svnCommits = SvnCommit.FindAllByProperty("Task", Task.Find(taskId));
            sb.Append("<table width=100% cellspacing=0><tr><td><b>Revision</b></td><td><b>User</b></td><td><b>Date</b></td></tr>");
            foreach (SvnCommit svn in svnCommits)
            {
                svnCount++;
                sb.Append("<tr bgcolor=\"#C7DCF5\"OnClick=\"showSvnCommit('svn" + svn.ID + "');\" OnMouseOver=\"this.style.backgroundColor='#9BC0ED';this.style.cursor='pointer';\" OnMouseOut=\"this.style.backgroundColor='#C7DCF5'\"><td>" + svn.Revision + "</td><td>" + svn.Member.FirstName + " " + svn.Member.LastName + "</td><td>" + svn.DateTime.ToShortDateString() + "</td></tr>");
                sb.Append("<tr id=\"svn" + svn.ID + "\" style=\"display:none\"><td colspan=3 style=\"font-size:11px;\">" + svn.Log.Replace(">", "&gt;").Replace("<", "&lt;").Replace("\n", "<br>") + "</td></tr>");
            }
            sb.Append("</table>");
            return sb.ToString();
        }

        private string BuildAttachmentList(int taskId)
        {
            StringBuilder sb = new StringBuilder();
            TaskAttachment[] taskAttachments = TaskAttachment.FindAllByProperty("TaskID", taskId);
            foreach (TaskAttachment ta in taskAttachments)
            {
                Attachment a = Attachment.Find(ta.AttachmentID) ?? new Attachment();
                if (a.ID > 0)
                {
                    attachmentCount++;
                    sb.Append("&nbsp;&nbsp;&nbsp;<a class=\"hrefTree\" href=\"attachments/" + a.Path + "\" target=\"_new\">" + a.Title + "</a><br><table><tr><td height=1></td></tr></table>");
                }
            }
            if (taskAttachments.Length.Equals(0))
            {
                sb.Append("No Attachments Associated.");
            }
            return sb.ToString();
        }

        private string[] BuildMemberList()
        {
            Member[] members = Member.FindAll(Order.Asc("LastName"), Expression.Eq("Terminated", false));
            string[] memberList = new string[members.Length + 1];
            int i = 1;
            memberList[0] = "0=Unassigned";
            foreach (Member member in members)
            {
                memberList[i] = member.ID + "=" + member.FirstName + " " + member.LastName;
                i++;
            }
            return memberList;
        }

        private string[] BuildTaskPriorityOptions(Priority[] priorities)
        {
            string[] priorityList = new string[priorities.Length];
            using (new SessionScope())
            {
                int i = 0;
                foreach (Priority priority in priorities)
                {
                    priorityList[i] = priority.ID + "=" + priority.Label;
                    i++;
                }
            }
            return priorityList;
        }

        private string[] BuildTaskComplexityOptions(TaskComplexity[] complexities)
        {
            string[] complexityList = new string[complexities.Length];
            using (new SessionScope())
            {
                int i = 0;
                foreach (TaskComplexity complexity in complexities)
                {
                    complexityList[i] = complexity.ID + "=" + complexity.Label;
                    i++;
                }
            }
            return complexityList;
        }

        private string[] BuildTaskTypeOptions(TaskType[] taskTypes)
        {
            string[] typeList = new string[taskTypes.Length];
            int i = 0;
            foreach (TaskType type in taskTypes)
            {
                typeList[i] = type.ID +"="+ type.Label;
                i++;
            }
            return typeList;
        }

        

        
    }
}